package io.gitee.pkmer.convention.page.query;

import io.gitee.pkmer.common.util.StrUtil;
import io.gitee.pkmer.convention.enums.BaseEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 胖卡
 * @version 1.0.0
 * @date 2024/6/27
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Schema(description = "筛选条件")
public class FilterCondition {
    @Schema(description = "字段名", example = "user_id")
    private String field;

    @Schema(description = "操作符", example = "=")
    private String operator;

    @Schema(description = "值", example = "3")
    private Object value;

    @Override
    public String toString() {
        return "FilterCondition{ " +
                field + " " + operator + " " + value +
                " }";
    }


    public static interface Operation{
        String EQ = "=";
        String GreaterOrEqual = ">=";
        String LessOrEqual = "<=";
        String LIKE = "LIKE";

         static String like(String value){
             if(StrUtil.isEmpty(value)) return null;
            return "%" + value + "%";
        }
    }

    public static FilterCondition of(String field, String operator, Object value){
        return FilterCondition.builder()
                .field(field)
                .operator(operator)
                .value(value).build();
    }

    public static Criteria createCriteria(){
        return new Criteria();
    }

    public static class Criteria{
        List<FilterCondition> conditions = new ArrayList<>();

        public Criteria and(String field, String operator, Object value){
            if(value == null) return this;
            if(value instanceof BaseEnum<?> baseEnum){
                conditions.add(FilterCondition.of(field, operator, baseEnum.getValue()));
            }else{
                conditions.add(FilterCondition.of(field, operator, value));
            }
            return this;
        }

        public List<FilterCondition> build(){
            return this.conditions;
        }
    }

}
